package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.common.constants.AdminConstants;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdUser> implements AdminLoginService {
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        //1 参数校验
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 判断用户名是否存在
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            //查无此人
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //3 判断状态是否有用 为9 才可用 取反
        if (!adUser.getStatus().equals(AdminConstants.USABLE)) {
            //暂时封禁
            if (adUser.getStatus().equals(AdminConstants.WHILE_UNUSABLE)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.WHILE_UNUSABLE);
            }
            //永久封禁
            if (adUser.getStatus().equals(AdminConstants.NEVER_UNUSABLE)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEVER_UNUSABLE);
            }
        }
        //4 比对密码
        //4.1 拿盐和输入密码进行MD5加密生成密文与数据库的密文对比
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        // 取反
        if (!md5DigestAsHex.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //5 生成token 返回
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //6 创建map集合封装数据
        Map<String,Object> map = new HashMap<>();
        //6.1 密码以及盐不能返回
        adUser.setPassword("");
        adUser.setSalt("");
        //7 封装数据
        map.put("user",adUser);
        map.put("token",token);
        //8 返回响应结果
        return ResponseResult.okResult(map);
    }
}
